package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.RabbitService;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {

    //  mapper: 主要负责查询数据库：与数据库交互获取数据！
    //  select * from base_category1 where is_deleted = 0; 用哪个mapper 主要看查询哪个表！
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    //  shift+f2
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitService rabbitService;


    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //  查询平台属性
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        //  判断
        if (baseAttrInfo!=null){
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        //  返回对象
        return baseAttrInfo;
    }

    @Override
    public IPage getSpuInfoList(Page<SpuInfo> spuInfoPage, Long category3Id) {
        //  select * from spu_info where category3_id = 61 order by id desc limit 0 ,2 ;
        LambdaQueryWrapper<SpuInfo> spuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spuInfoLambdaQueryWrapper.eq(SpuInfo::getCategory3Id,category3Id);
        spuInfoLambdaQueryWrapper.orderByDesc(SpuInfo::getId);
        return spuInfoMapper.selectPage(spuInfoPage,spuInfoLambdaQueryWrapper);
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        //  返回数据.
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        /*
        spu_image
        spu_info  商品信息表
        spu_poster
        spu_sale_attr
        spu_sale_attr_value
         */

        spuInfoMapper.insert(spuInfo);

        //  获取图片列表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)){
            spuImageList.forEach(spuImage -> {
                //  赋值spuId
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }

        //  获取海报信息.
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)){
            spuPosterList.forEach(spuPoster -> {
                //  赋值spuId
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            });
        }

        //  销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
            spuSaleAttrList.forEach(spuSaleAttr -> {
                //  赋值spuId
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                        //  赋值spuId
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        // sale_attr_name
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }
    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        //  select * from spu_image where spu_id = ?
        LambdaQueryWrapper<SpuImage> spuImageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spuImageLambdaQueryWrapper.eq(SpuImage::getSpuId,spuId);
        return spuImageMapper.selectList(spuImageLambdaQueryWrapper);
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        //  多表关联查询: 推荐使用xml 服务层方法命名：get/find save remove mapper: select insert delete
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        /*
        sku_attr_value
        sku_image
        sku_info
        sku_sale_attr_value
         */

        //  sku_info    ---> 插入完成之后能够自动获取到skuInfo.id;
        skuInfoMapper.insert(skuInfo);

        //  sku_image
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)){
            skuImageList.forEach(skuImage -> {
                //  赋值skuId
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }

        //  sku_attr_value  skuId 与 平台属性值Id 的中间表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)){
            skuAttrValueList.forEach(skuAttrValue -> {
                //  赋值skuId
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }

        //  sku_sale_attr_value skuId 与 销售属性值Id 的中间表
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)){
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                //  赋值skuId
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                //  赋值spuId = spuInfo.getId(); = skuInfo.getspuId();
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
        //  将数据添加到布隆过滤器中
        RBloomFilter<Object> bloomFilter = this.redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
        bloomFilter.add(skuInfo.getId());

        //  上架： skuInfo.setIsSale(1); this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    @Override
    public IPage<SkuInfo> getSkuInfoList(Page<SkuInfo> skuInfos, Long category3Id) {
        //  构建条件
        LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        skuInfoLambdaQueryWrapper.eq(SkuInfo::getCategory3Id,category3Id).orderByDesc(SkuInfo::getId);
        //  select * from sku_info where category3Id=? order by id desc limit ?,?;
        //  select * from sku_info where category3Id=? order by id desc limit (pageNo-1)*pageSize,pageSize;
        return skuInfoMapper.selectPage(skuInfos,skuInfoLambdaQueryWrapper);
    }

    @Override
    public void onSale(Long skuId) {

        //  数据库发生了变化；则需要保证缓存数据一致！  mysql 与 redis 数据同步！
        //  sku:[21]:info
        String skuKey = RedisConst.SKUKEY_PREFIX+"["+skuId+"]"+RedisConst.SKUKEY_SUFFIX;
        this.redisTemplate.delete(skuKey);
        //  update sku_info set is_sale = 1 where sku_id = ?;
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);

        //  睡眠.
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //  再删除.
        this.redisTemplate.delete(skuKey);
        //  商品上架：
        //  发送的消息内容是谁?  是由消费者决定的！
        this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);

    }

    @Override
    public void cancelSale(Long skuId) {
        //  组成缓存的key;
        String skuKey = RedisConst.SKUKEY_PREFIX+"["+skuId+"]"+RedisConst.SKUKEY_SUFFIX;
        this.redisTemplate.delete(skuKey);
        //  update sku_info set is_sale = 0 where sku_id = ?;
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
        //  睡眠.
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //  再删除.
        this.redisTemplate.delete(skuKey);
        //  商品下架：
        //  发送的消息内容是谁?  是由消费者决定的！
        this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @Override
    @GmallCache(prefix = "sku:")
    public SkuInfo getSkuInfo(Long skuId) {

        //  return getSkuInfoByRedisson(skuId);
        //  return getSkuInfoByRedis(skuId);
        return getInfo(skuId);
    }

    private SkuInfo getSkuInfoByRedisson(Long skuId) {
        //  从数据库获取数据
        SkuInfo skuInfo = null;
        //  sku:skuId:info;
        String skuKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKUKEY_SUFFIX;
        try {
            //  RedisTemplate
            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            //  判断：缓存中是否有数据
            if (skuInfo==null){
                //  缓存中没有. 从数据库中获取数据. sku:skuId:lock;
                String skuLocKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                RLock lock = this.redissonClient.getLock(skuLocKey);
                //  上锁
                lock.lock();
                try {
                    //  业务逻辑.
                    //  上锁成功： 查询数据库。
                    skuInfo = getInfo(skuId);
                    if (skuInfo==null){
                        SkuInfo skuInfo1 = new SkuInfo();
                        //  防止缓存穿透，设置一个 空对象。
                        this.redisTemplate.opsForValue().setIfAbsent(skuKey, skuInfo1, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfo1;
                    }else {
                        //  商品详情的过期时间
                        this.redisTemplate.opsForValue().setIfAbsent(skuKey, skuInfo, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfo;
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //  解锁
                    lock.unlock();
                }

            }else {
                //  缓存有数据
                return skuInfo;
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return getInfo(skuId);
    }

    private SkuInfo getSkuInfoByRedis(Long skuId) {
        //  从数据库获取数据
        SkuInfo skuInfo = null;
        //  判断缓存中是否存在！
        //  数据类型：Hash --> SkuInfo 好处便于修改，修改的时候不需要反序列其他属性数据！
        //  商品详情只展示数据： String 数据类型：
        try {
            //  sku:skuId:info;
            String skuKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKUKEY_SUFFIX;
            //  RedisTemplate
            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            //  判断：缓存中是否有数据
            if (skuInfo==null){
                //  缓存中没有. 从数据库中获取数据. sku:skuId:lock;
                String skuLocKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                //  声明一个随机不可猜测的uuid
                String uuid = UUID.randomUUID().toString();
                //  分布式锁： redis set key value ex timeout nx;
                Boolean result = this.redisTemplate.opsForValue().setIfAbsent(skuLocKey, uuid, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if (result){
                    //  上锁成功： 查询数据库。
                    skuInfo = getInfo(skuId);
                    if (skuInfo==null){
                        SkuInfo skuInfo1 = new SkuInfo();
                        //  防止缓存穿透，设置一个 空对象。
                        this.redisTemplate.opsForValue().setIfAbsent(skuKey, skuInfo1, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        //  释放锁的方法.
                        extracted(skuLocKey, uuid);
                        return skuInfo1;
                    }else {
                        //  商品详情的过期时间
                        this.redisTemplate.opsForValue().setIfAbsent(skuKey, skuInfo, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                        //  释放锁的方法.
                        extracted(skuLocKey, uuid);
                        return skuInfo;
                    }
                }else {
                    //  等待自旋
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return getSkuInfo(skuId);
                }
            }else {
                //  缓存有：直接返回
                return skuInfo;
            }
        } catch (RuntimeException e) {
            //  记录日志信息.
            e.printStackTrace();
        }
        //  从数据库获取数据
        return getInfo(skuId);
    }

    /**
     * 释放锁的方法.
     * @param skuLocKey
     * @param uuid
     * ctrl+alt+m
     */
    private void extracted(String skuLocKey, String uuid) {
        //  释放锁资源：
        //  声明一个lua脚本：·
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setScriptText(scriptText);
        defaultRedisScript.setResultType(Long.class);
        //  RedisScript: key的集合 value; 释放锁
        this.redisTemplate.execute(defaultRedisScript, Arrays.asList(skuLocKey), uuid);
    }

    private SkuInfo getInfo(Long skuId) {
        //  select * from sku_info where id = ?
        //  select * from sku_image where sku_id = ?;
        //  123 ; skuInfo == null
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //  业务层面如何防止空指针
        if (skuInfo!=null){
            LambdaQueryWrapper<SkuImage> skuImageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            skuImageLambdaQueryWrapper.eq(SkuImage::getSkuId, skuId);
            skuInfo.setSkuImageList(skuImageMapper.selectList(skuImageLambdaQueryWrapper));
        }
        //  返回数据.
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "categoryView:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        //  查询数据
        return this.baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        String locKey = "price:"+skuId+":lock";
        RLock lock = redissonClient.getLock(locKey);
        lock.lock();
        try {
            //  select price from sku_info where id = 24;
            //  select * from sku_info where id = 24;
            //  SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
            LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //  设置的查询条件
            skuInfoLambdaQueryWrapper.eq(SkuInfo::getId,skuId);
            //  查询的字段
            skuInfoLambdaQueryWrapper.select(SkuInfo::getPrice);
            SkuInfo skuInfo = skuInfoMapper.selectOne(skuInfoLambdaQueryWrapper);
            if (skuInfo!=null){
                //  返回数据.
                return skuInfo.getPrice();
            }
            return new BigDecimal("0");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    @Override
    @GmallCache(prefix = "getSpuSaleAttrListCheckBySku:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListBySkuIdAndSpuId(skuId,spuId);
    }

    @Override
    @GmallCache(prefix = "getSkuValueIdsMap:")
    public Map getSkuValueIdsMap(Long spuId) {
        //  创建map 一个集合.
        HashMap<Object, Object> map = new HashMap<>();
        //  给map 赋值： map.put("key","value");
        //  key = value_ids  value = skuId
        //  调用sql 语句查询数据：返回值：List<Map> 或 List<Pojo>
        //  Map 可以与 Pojo 互换！
        //  key=property value=propertyValue
        //  get()=map.get(key) set=map.put(key,value);
        List<Map> list = skuSaleAttrValueMapper.selectSkuValueIds(spuId);
        //  循环遍历.
        list.forEach(map1 -> {
            map.put(map1.get("value_ids"),map1.get("sku_id"));
        });
        //  返回数据》
        return map;
    }

    @Override
    @GmallCache(prefix = "getSpuPosterBySpuId:")
    public List<SpuPoster> getSpuPosterBySpuId(Long spuId) {
        return spuPosterMapper.selectList(new LambdaQueryWrapper<SpuPoster>().eq(SpuPoster::getSpuId,spuId));
    }

    @Override
    @GmallCache(prefix = "getAttrList:")
    public List<BaseAttrInfo> getAttrList(Long skuId) {

        //  调用mapper
        return this.baseAttrInfoMapper.selectAttrList(skuId);
    }

    @Override
    @GmallCache(prefix = "categoryList:")
    public List<JSONObject> getCategoryList() {
        //  声明一个集合
        List<JSONObject> list = new ArrayList<>();
        //  声明一个index 变量
        int index = 1;
        //  数据来源： select * from base_category_view
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        //  获取到集合数据. 按照一级分类Id 进行分组获取数据. select category1_id, category1_name from base_category_view group by category1_id,category1_name;
        //  key = category1Id; value = List<BaseCategoryView>;
        Map<Long, List<BaseCategoryView>> baseCategory1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //  循环遍历
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = baseCategory1Map.entrySet().iterator();
        //  判断是否有下一个数据
        while (iterator.hasNext()){
            //  获取到数据对象.
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            //  获取一级分类id
            Long category1Id = entry.getKey();
            //  获取一级分类Id 对应的集合数据.
            List<BaseCategoryView> baseCategoryViewList1 = entry.getValue();
            //  创建一个category1 对象
            JSONObject category1 = new JSONObject();
            category1.put("index",index);
            category1.put("categoryId",category1Id);
            category1.put("categoryName",baseCategoryViewList1.get(0).getCategory1Name());
            //  category1.put("categoryChild","二级分类集合");
            //  变量迭代
            index++;
            //  一级下的二级分类数据
            Map<Long, List<BaseCategoryView>> baseCategory2Map = baseCategoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));

            //  创建一个存储二级分类集合对象
            ArrayList<JSONObject> categoryChild2 = new ArrayList<>();
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = baseCategory2Map.entrySet().iterator();
            while (iterator1.hasNext()){
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                //  获取二级分类Id
                Long category2Id = entry1.getKey();
                //  获取二级分类对应的数据
                List<BaseCategoryView> baseCategoryViewList2 = entry1.getValue();
                //  创建一个category2 对象
                JSONObject category2 = new JSONObject();
                category2.put("categoryId",category2Id);
                category2.put("categoryName",baseCategoryViewList2.get(0).getCategory2Name());
                //  category2.put("categoryChild","二级下的三级分类数据");
                //  获取二级分类下的三级分类数据.
                List<JSONObject> categoryChild3 = baseCategoryViewList2.stream().map(baseCategoryView -> {
                    //  创建一个category3 对象
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId", baseCategoryView.getCategory3Id());
                    category3.put("categoryName", baseCategoryView.getCategory3Name());
                    return category3;
                }).collect(Collectors.toList());
                category2.put("categoryChild",categoryChild3);
                //  将电子书刊，音像，英文原版... 等数据放入集合，后续将这个集合存储到 图书、音像、电子书刊
                categoryChild2.add(category2);
            }
            //  二级下的三级分类数据
            category1.put("categoryChild",categoryChild2);
            //  将category1 添加到集合中
            list.add(category1);
        }
        //  返回数据。 map.put("list","sss");
        return list;
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //  select * from base_attr_value where attr_id = 1;
        LambdaQueryWrapper<BaseAttrValue> baseAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseAttrValueLambdaQueryWrapper.eq(BaseAttrValue::getAttrId,attrId);
        return baseAttrValueMapper.selectList(baseAttrValueLambdaQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 只要有一次就回滚数据. 如果没有rollbackFor = Exception.class 默认 RuntimeException
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //  保存：id null 修改 id!=null
        if (baseAttrInfo.getId()!=null){
            //  修改：base_attr_info 或 base_attr_value:
            baseAttrInfoMapper.updateById(baseAttrInfo);
            //  attr_id = baseAttrInfo.getId();
            //  先删除，再新增！    delete from base_attr_value where attr_id = ?;  物理删除.
            //  update base_attr_value set is_delete = 1 where attr_id = ?; 逻辑删除
            LambdaQueryWrapper<BaseAttrValue> baseAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            baseAttrValueLambdaQueryWrapper.eq(BaseAttrValue::getAttrId,baseAttrInfo.getId());
            baseAttrValueMapper.delete(baseAttrValueLambdaQueryWrapper);

        } else {
            //  base_attr_info 平台属性数据保存.
            baseAttrInfoMapper.insert(baseAttrInfo);
        }

        /*
        base_attr_info
        base_attr_value
        使用mapper
         */

        //   @TableId(type = IdType.AUTO) 表示获取到插入之后的主键值！
        //  获取到平台属性值
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //  base_attr_value
        if (!CollectionUtils.isEmpty(attrValueList)){
            //  函数式接口  复制小括号，写死右箭头，落地大括号！
            //  t: attrValueList 集合泛型
            attrValueList.forEach((baseAttrValue)->{
                //  attr_id 赋值  = base_attr_info.id;
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                //  调用插入方法.
                baseAttrValueMapper.insert(baseAttrValue);
            });
        }
    }

    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        /*
        # 多表关联查询
        select  * from base_attr_info bai inner join base_attr_value bav
                  on bai.id = bav.attr_id
                  where
            (category_id = ? and category_level = 1
                or category_id = ? and category_level = 2
                or category_id = ? and category_level = 3);
         */
        //  多表关联时，mapper 的选择： 使用一的mapper！
        return baseAttrInfoMapper.selectAttrInfoList(category1Id,category2Id,category3Id);
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //  构建查询条件：
        //  select * from base_category3 where category2_id = 13 // order by id desc;
        //  select * from base_category3 where category2_id = ? // order by id desc;
        //  不添加排序：那么默认是按照哪种方式进行排序的? 升序！ where
        QueryWrapper<BaseCategory3> baseCategory3QueryWrapper = new QueryWrapper<>();
        baseCategory3QueryWrapper.eq("category2_id",category2Id);
        //  baseCategory3QueryWrapper.orderByDesc("id");
        return baseCategory3Mapper.selectList(baseCategory3QueryWrapper);
    }

    //  ctrl+i
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //  select * from base_category2 where category1_id = 2 ;
        //  Wrapper：构建条件：查询 删除 修改 T：泛型 对应的实体类
        //        QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
        //        baseCategory2QueryWrapper.eq("category1_id",category1Id);
        //        return baseCategory2Mapper.selectList(baseCategory2QueryWrapper);

        //  LambdaUpdateWrapper
        LambdaQueryWrapper<BaseCategory2> baseCategory2LambdaQueryWrapper = new LambdaQueryWrapper<>();
        //  :: 方法引用 java 基础。           BaseCategory2::getCategory1Id category1_id = category1Id
        baseCategory2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id,category1Id);
        //  where category1_id = 2 ;
        //  Wrapper 是构建条件用的！
        //  baseCategory2Mapper.selectList();

        return baseCategory2Mapper.selectList(baseCategory2LambdaQueryWrapper);

    }

    @Override
    public List<BaseCategory1> getCategory1() {
        //  调用方法. select * from base_category1;
        return baseCategory1Mapper.selectList(null);
    }
}
